<template>
    <div v-if="modelValue == STATUS.SKUFORM">
        <el-form :label-width="100">
            <el-form-item label="SPU名称">
                <div>{{ spuInfo?.spuName }}</div>
            </el-form-item>
            <el-form-item label="SKU名称">
                <el-input type="text" placeholder="SKU名称" v-model="skuForm.skuName"></el-input>
            </el-form-item>
            <el-form-item label="价格(元)">
                <el-input type="number" placeholder="价格(元)" v-model="skuForm.price"></el-input>
            </el-form-item>
            <el-form-item label="重量(千克)">
                <el-input type="number" placeholder="重量(千克)" v-model="skuForm.weight"></el-input>
            </el-form-item>
            <el-form-item label="规格描述">
                <el-input type="textarea" placeholder="规格描述" rows="3" v-model="skuForm.skuDesc"></el-input>
            </el-form-item>
            <el-form-item label="平台属性">
                <el-form :inline="true">
                    <el-form-item :label="attr.attrName" v-for="attr in attrList" :key="attr.id">
                        <el-select placeholder="请选择" v-model="attr.attrIdValId">
                            <el-option v-for="attrVal in attr.attrValueList" :key="attrVal.id"
                                :label="attrVal.valueName" :value="`${attr.id}:${attrVal.id}`">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-form-item>
            <el-form-item label="销售属性">
                <el-form :inline="true">
                    <el-form-item :label="saleAttr.saleAttrName" v-for="saleAttr in spuSaleAttrList" :key="saleAttr.id">
                        <el-select placeholder="请选择" v-model="saleAttr.saleAttrIdValId">
                            <el-option v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                                :label="saleAttrValue.saleAttrValueName" :value="`${saleAttr.id}:${saleAttrValue.id}`">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </el-form-item>
            <el-form-item label="图片列表">
                <el-table :data="spuImgList" border @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="80" align="center" />
                    <el-table-column label="图片">
                        <template #default="{ row, $index }">
                            <img :src="row.imgUrl" width="80" height="80">
                        </template>
                    </el-table-column>
                    <el-table-column label="名称" prop="imgName" />
                    <el-table-column label="操作" width="100">
                        <template #default="{ row, $index }">
                            <el-tag type="success" size="small" v-if="row.isDefault == '1'">默认</el-tag>
                            <el-button type="primary" size="small" v-else @click="setDefault(row)">设为默认</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" size="default" @click="onSave">保存</el-button>
                <el-button @click="onCancelSave">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang="ts">
import { STATUS } from '../../index.vue'
import Pubsub from 'pubsub-js'
import { ref } from 'vue';
import type { saleAttrModel, spuImageModel, spuModel } from '@/api/spu';
import spuApi from '@/api/spu';
import { ElMessage } from 'element-plus';
import type { attrInfoModel } from '@/api/attr';
import attr from '@/api/attr';
import useCategoryStore from '@/stores/category'
import type { SkuModel } from '@/api/sku';
import skuApi from '@/api/sku';
const categoryStore = useCategoryStore();
defineProps<{
    modelValue: number
}>()
const emit = defineEmits<{
    (event: 'update:modelValue', status: number): void
}>()
const spuInfo = ref<spuModel>()
const spuImgList = ref<spuImageModel[]>([])
const spuSaleAttrList = ref<saleAttrModel[]>([])
const attrList = ref<attrInfoModel[]>([])
const initSkuForm = (): SkuModel => ({
    spuId: undefined,
    tmId: undefined,
    category3Id: undefined,
    price: '',
    skuName: '',
    skuDesc: '',
    weight: '',
    createTime: '',
    skuDefaultImg: '',
    skuAttrValueList: [],
    skuSaleAttrValueList: [],
    skuImageList: []
})
const skuForm = ref(initSkuForm());
// 获取平台属性
const getAttrList = async () => {
    let { category1Id, category2Id, category3Id } = categoryStore;
    try {
        let result = await attr.getAttrInfo(category1Id!, category2Id!, category3Id!)
        attrList.value = result
    } catch (error) {
        ElMessage.error('获取平台属性失败,请重试')
    }
}
// 获取销售属性
const getSpuSaleAttrList = async () => {
    try {
        let result = await spuApi.spuSaleAttrList(spuInfo.value?.id!)
        spuSaleAttrList.value = result;
    } catch (error) {
        ElMessage.error('获取平台属性失败,请重试')
    }
}
// 获取图片列表
const getSpuImageList = async () => {
    try {
        let result = await spuApi.spuImageList(spuInfo.value?.id!)
        spuImgList.value = result
    } catch (error) {
        ElMessage.error('获取图片列表失败,请重试')
    }
}
// 获取当前的spu
const getSpu = (type: string, val: spuModel) => {
    spuInfo.value = val;
    getAttrList();
    getSpuSaleAttrList();
    getSpuImageList();
}
Pubsub.subscribe('getSpu', getSpu)
// 选择器
const handleSelectionChange = (val: spuImageModel[]) => {
    skuForm.value.skuImageList = val
}
// 设置默认图片
const setDefault = (row: spuImageModel) => {
    spuImgList.value.forEach(item => { item.isDefault = '0' })
    row.isDefault = '1'
    skuForm.value.skuDefaultImg = row.imgUrl
}
// 取消
const onCancelSave = () => {
    emit('update:modelValue', STATUS.SPULIST)
}
// 保存
const onSave = async () => {
    // 组装平台属性
    attrList.value.forEach(attr => {
        if (attr.attrIdValId) {
            const [attrId, valueId] = attr.attrIdValId.split(':');
            skuForm.value.skuAttrValueList.push({
                attrId,
                valueId
            })
        }
    })
    // 写法2
    // attrList.value.filter(attr => attr.attrIdValId).forEach(item => {
    //     const [attrId, valueId] = (item.attrIdValId as string).split(':')
    //     skuForm.value.skuAttrValueList.push({
    //         attrId,
    //         valueId
    //     })
    // })
    // 组装销售属性 
    spuSaleAttrList.value.forEach(saleAttr => {
        if (saleAttr.saleAttrIdValId) {
            const [saleAttrId, saleAttrValueId] = saleAttr.saleAttrIdValId.split(':')
            skuForm.value.skuSaleAttrValueList.push({
                saleAttrId,
                saleAttrValueId
            })
        }
    })
    skuForm.value.spuId = spuInfo.value?.id
    skuForm.value.tmId = spuInfo.value?.tmId
    skuForm.value.category3Id = spuInfo.value?.category3Id
    try {
        await skuApi.save(skuForm.value)
        ElMessage.success('保存成功')
    } catch (error) {
        ElMessage.error('保存失败')
    }
    emit('update:modelValue', STATUS.SPULIST)
    Pubsub.publish('update');
}
</script>

<style scoped>

</style>